package cn.cnsy123.blog.application.service.impl;

import cn.cnsy123.blog.application.constants.CacheRedisConstant;
import cn.cnsy123.blog.application.dao.UserDataCountInfoRepository;
import cn.cnsy123.blog.application.dao.UserInfoRepository;
import cn.cnsy123.blog.application.dao.UserLoginRepository;
import cn.cnsy123.blog.application.encoder.PasswordEncoder;
import cn.cnsy123.blog.application.entity.UserDataCountInfo;
import cn.cnsy123.blog.application.entity.UserLoginInfo;
import cn.cnsy123.blog.application.entity.UserPersonalInfo;
import cn.cnsy123.blog.application.http.request.UserLoginRequest;
import cn.cnsy123.blog.application.http.request.UserRegisterRequest;
import cn.cnsy123.blog.application.http.response.UserLoginResponse;
import cn.cnsy123.blog.application.http.response.UserRegisterResponse;
import cn.cnsy123.blog.application.service.UserInfoService;
import cn.cnsy123.blog.application.util.PassWordUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Optional;
import java.util.UUID;

/**
 * @author yangpengfei
 * @description 用户信息处理-核心逻辑
 * @date 2019-10-15 16-07-55
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {

    private static final Logger logger = LoggerFactory.getLogger(UserInfoServiceImpl.class);

    @Autowired
    private UserLoginRepository userLoginRepository;

    @Autowired
    private UserInfoRepository userInfoRepository;

    @Autowired
    private UserDataCountInfoRepository userDataCountInfoRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    @Transactional
    public UserRegisterResponse saveUserInfo(UserRegisterRequest request) {

        UserRegisterResponse response = null;
        try {
            response = new UserRegisterResponse();

            Optional<UserLoginInfo> userInfo = userLoginRepository.findByUserName(request.getUserName());
            if(userInfo != null && userInfo.isPresent()){
                response.setResultCode("1005");
                response.setMsg("注册用户名已存在");
            }else{
                Optional<UserLoginInfo> userInfo1 = userLoginRepository.findByUserMail(request.getUserMail());
                if(userInfo1 != null && userInfo1.isPresent()){
                    response.setResultCode("1005");
                    response.setMsg("注册邮箱已存在");
                }else{
                    Optional<UserLoginInfo> userInfo2 = userLoginRepository.findByUserPhone(request.getUserPhone());
                    if(userInfo2 != null && userInfo2.isPresent()){
                        response.setResultCode("1005");
                        response.setMsg("注册手机号已存在");
                    }else{
                        String passSalt = PassWordUtil.generatePassSalt();

                        String encryptPass = passwordEncoder.encode(request.getPassWord(),passSalt);

                        String userId = UUID.randomUUID().toString();

                        logger.info("加密后的密码:{}",encryptPass);

                        UserLoginInfo userLoginInfo = new UserLoginInfo(request.getUserMail(), request.getUserPhone(),
                                request.getUserName(), encryptPass, passSalt,
                                new Date(System.currentTimeMillis()));
                        userLoginInfo.setUserId(userId);
                        //保存用户登录信息
                        UserLoginInfo saveResult = userLoginRepository.save(userLoginInfo);

                        UserPersonalInfo userPersonalInfo = new UserPersonalInfo(userId,request.getUserNickName());
                        //保存用户个人信息
                        UserPersonalInfo saveUserPersonal = userInfoRepository.save(userPersonalInfo);

                        //初始化用户统计信息
                        UserDataCountInfo userDataCountInfo = new UserDataCountInfo(userId,0L,0L,0L,0L,0L,0L,0L,0L);
                        userDataCountInfoRepository.save(userDataCountInfo);

                        if(saveResult != null && saveUserPersonal != null){
                            response.setResultCode("0000");
                            response.setMsg("注册成功");
                        }else{
                            response.setResultCode("1002");
                            response.setMsg("注册失败，请检查各项参数是否正确");
                        }
                    }
                }


            }
        } catch (Exception e) {
            throw new RuntimeException("用户注册失败",e);
        }
        return response;
    }

    @Override
    @Transactional
    public UserLoginResponse loginCore(UserLoginRequest request) {

        UserLoginResponse response = new UserLoginResponse();
        try {
            //图形验证码校验
            String captchaContent = stringRedisTemplate.opsForValue().get(new StringBuilder(CacheRedisConstant.IMAGE_CACHE_PREFIX).append(request.getCacheKey()).toString());
            //如果验证码已过期
            if(StringUtils.isBlank(captchaContent)){
                response.setResultCode("1009");
                response.setMessage("图形验证码已过期，请重新获取");
            }else{
                //如果验证码校验通过
                if(StringUtils.equalsIgnoreCase(request.getImgCode(),captchaContent)){
                    Optional<UserLoginInfo> optionalUserLoginInfo = userLoginRepository.findByUserName(request.getUserName());
                    //判断当前用户名对应的登录信息是否存在
                    if (optionalUserLoginInfo != null && optionalUserLoginInfo.isPresent()) {
                        UserLoginInfo userLoginInfo = optionalUserLoginInfo.get();
                        //如果密码输入正确，表示信息匹配，登录成功
                        boolean flag = passwordEncoder.equals(userLoginInfo.getPassWord(), request.getPassWord(), userLoginInfo.getPassSalt());
                        if (flag) {
                            response.setResultCode("0000");
                            response.setMessage("登录成功");
                        } else {
                            response.setResultCode("1004");
                            response.setMessage("密码匹配失败，请重新输入");
                        }

                    } else {
                        response.setResultCode("1003");
                        response.setMessage("登录用户不存在，请确认用户名是否输入正确");
                    }
                }else{
                    response.setResultCode("1008");
                    response.setMessage("图形验证码输入错误，请重新输入");
                }
            }

        }catch (Exception e){
            throw new RuntimeException("登录异常失败",e);
        }

        return response;
    }
}
